import java.util.List;
import java.util.UUID;

public class FrontDesk extends User {
    public FrontDesk(String id, String username, String password, String phone) {
        super(id, username, password, phone, "前台");
    }

    @Override
    public boolean login(String password) {
        if (locked) {
            System.out.println("账户已锁定");
            return false;
        }
        if (this.password.equals(password)) {
            loginAttempts = 0;
            return true;
        } else {
            loginAttempts++;
            if (loginAttempts >= 5) {
                locked = true;
                System.out.println("密码错误次数过多，账户已锁定");
            }
            return false;
        }
    }

    public Ticket sellTicket(Show show, List<String> seatIds, String customerPhone) {
        for (String seatId : seatIds) {
            Seat seat = show.getHall().getSeats().stream()
                    .filter(s -> s.getId().equals(seatId) && !s.isSold())
                    .findFirst().orElseThrow(() -> new IllegalArgumentException("座位[" + seatId + "]已售出或不存在"));
            seat.setSold(true);
        }
        Ticket ticket = new Ticket(UUID.randomUUID().toString(), show, seatIds, customerPhone, show.getPrice());
        show.getTickets().add(ticket);
        Log.record("售票", "售出影片[" + show.getMovie().getName() + "]的票", this.username);
        return ticket;
    }

    public void refundTicket(String ticketId, List<Show> shows) {
        Ticket ticket = null;
        Show targetShow = null;
        for (Show show : shows) {
            for (Ticket t : show.getTickets()) {
                if (t.getId().equals(ticketId)) {
                    ticket = t;
                    targetShow = show;
                    break;
                }
            }
            if (ticket != null) break;
        }
        if (ticket == null) {
            throw new IllegalArgumentException("票不存在");
        }
        long diff = targetShow.getShowTime().getTime() - System.currentTimeMillis();
        if (diff < 3600 * 1000) {
            throw new IllegalArgumentException("距离放映不足1小时，不能退票");
        }
        for (String seatId : ticket.getSeatIds()) {
            targetShow.getHall().getSeats().stream()
                    .filter(s -> s.getId().equals(seatId))
                    .findFirst().ifPresent(s -> s.setSold(false));
        }
        targetShow.getTickets().remove(ticket);
        Log.record("退票", "退掉票[" + ticketId + "]", this.username);
    }
}